package filters

import (
	"bytes"
	"compress/zlib"
	"github.com/pkg/errors"
	"io"
)

type FlateDecodeFilter struct {
}

func (this *FlateDecodeFilter) Encode(bs []byte) ([]byte, error) {
	rst := bytes.NewBuffer(make([]byte, 0, len(bs)))
	writer := zlib.NewWriter(rst)
	_, err := writer.Write(bs)
	if err != nil {
		return nil, errors.Wrapf(err, "zlib压缩")
	}
	err = writer.Close()
	if err != nil {
		return nil, errors.Wrapf(err, "关闭压缩流")
	}
	return rst.Bytes(), nil
}
func (this *FlateDecodeFilter) Decode(bs []byte) ([]byte, error) {

	reader, err := zlib.NewReader(bytes.NewReader(bs))
	if err != nil {
		return nil, errors.Wrapf(err, "创建解压reader")
	}
	defer reader.Close()

	dataBytes, err := io.ReadAll(reader)
	if err != nil {
		return nil, errors.Wrapf(err, "读取解压数据")
	}
	return dataBytes, nil
}
